import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

///Android的ocr texture view，用于处理flutter展示Android camera view控件时聚焦卡顿问题
class OcrAndroidTextureView extends StatefulWidget {
  final PlatformViewCreatedCallback onPlatformViewCreated;
  final dynamic creationParams;

  const OcrAndroidTextureView(
      {Key? key, required this.onPlatformViewCreated, this.creationParams})
      : super(key: key);

  @override
  State<StatefulWidget> createState() => _OcrAndroidTextureView();
}

///检查 是否可以使用 texture的摄像机
Future<Map> canUseTexture() {
  return MethodChannel("com.jacky.util/ocr_view_msg")
      .invokeMethod("canUse")
      .then((value) {
    return value is Map ? value : {};
  }).onError((error, stackTrace) {
    print("flutter canUseTexture onError $error");
    return {};
  });
}

class _OcrAndroidTextureView extends State<OcrAndroidTextureView> {
  final MethodChannel startChannel = MethodChannel("com.jacky.util/ocr_view_msg");
  int? _cameraId;

  @override
  void initState() {
    super.initState();
    Future.delayed(const Duration(milliseconds: 300), () {
      //print("ocr android view init ---------------");
      Map map = widget.creationParams is Map
          ? widget.creationParams
          : {"cameraFont": false};
      startChannel.invokeMethod("initCamera", map).then((value) {
        //print("ocr android view init end---------------$value");
        if (value is Map && value['cameraId'] != null) {
          var cameraId = value['cameraId'];
          int id = cameraId is int ? cameraId : int.tryParse("$cameraId")??0;
          _cameraId = id;
          widget.onPlatformViewCreated(id);
          if(mounted)setState(() {});
        }
      }).catchError((e) {
        print("ocr android view init error----------------$e");
      });
    });
    startChannel.setMethodCallHandler((call) async{
      print("----startChannel not handled--- method ${call.method} ${call.arguments is Map} ${call.arguments}");

    });
  }

  @override
  Widget build(BuildContext context) {
    if(_cameraId == null) return Container();
    return Texture(textureId: _cameraId!);
  }
}
